import { exec } from 'child_process';
import * as path from 'path';

// 执行 Git 命令获取所有分支
export function getAllGitBranches(repoPath = '.', showRemote = false) {
  return new Promise((resolve, reject) => {
    // 使用 git branch -a 获取所有分支（包括远程分支）
    const command = `pwd && git -C ${repoPath} for-each-ref --sort=-committerdate ${showRemote ? 'refs/remotes/' : 'refs/heads/'} --format='%(refname:short)'
`;

    exec(command, (error, stdout, stderr) => {
      if (error) {
        return reject(`Error executing git command: ${stderr || error.message}`);
      }
      // 解析输出，提取分支名称
      const branches = stdout
        .split('\n') // 按行分割
        ?.map(branch => branch.trim()) // 去除多余空格
        ?.filter(branch => branch.length > 0) // 过滤掉空行
        ?.map(branch => branch.replace('* ', '').trim()); // 去掉当前分支前的星号标记

      resolve(branches);
    });
  });
}

/** 删除 git 分支 */
export function deleteGitBranch(branchName: string, repoPath = '.') {
  return new Promise((resolve, reject) => {
    const command = `git -C ${repoPath} branch -D ${branchName}`;

    exec(command, (error, stdout, stderr) => {
      if (error) {
        return reject(`Error deleting branch: ${stderr || error.message}`);
      }
      resolve(stdout);
    });
  });
}

/* 切换分支 */
export function switchGitBranch(branchName: string, repoPath = '.') {
  return new Promise((resolve, reject) => {
    const command = `git -C ${repoPath} checkout ${branchName}`;

    exec(command, (error, stdout, stderr) => {
      if (error) {
        return reject(`Error switching branch: ${stderr || error.message}`);
      }
      resolve(stdout);
    });
  });
}


/** 获取子树项目的所有分支 */
export function getSubtreeBranches(repoPath = '.'): Promise<string[]> {
  console.log('repoPath', repoPath);
  return new Promise((resolve, reject) => {
    const command = `git ls-remote --heads ${repoPath}`;

    exec(command, (error, stdout, stderr) => {
      if (error) {
        return reject(`Error switching branch: ${stderr || error.message}`);
      }

      // if (stderr) {
      //   console.error(`命令输出错误: ${stderr}`);
      //   return;
      // }


      // 解析输出并提取分支名
      const branches = stdout
        .split('\n') // 按行分割输出
        .filter(line => line.trim() !== '') // 去除空行
        ?.map(line => line.split('\t')[1]) // 提取第二列（refs/heads/<branch-name>）
        ?.map(ref => ref.replace('refs/heads/', '')); // 去掉 "refs/heads/" 前缀

      // 输出分支名数组
      resolve(branches);
    });
  });
}


